package entity

import (
	dbconnector "YingShop/dbConnector"
	"YingShop/log"
	"YingShop/model"
	"errors"
	"fmt"

	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
)

type ShopProduct struct {
	ProductId    int
	ProductName  string
	ProductDesc  string
	ProductNum   int
	ProductPrice float64
	ProductImg   string
	ProductVideo string
}

func (product *ShopProduct) Load() error {
	conn := dbconnector.GetDb()
	productModel := model.ShopProduct{}
	result := conn.First(&productModel, product.ProductId)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return fmt.Errorf("找不到id为%d的商品", product.ProductId)
		} else {
			log.Error(result.Error.Error())
			return errors.New("未知错误")
		}
	}
	product.ProductName = productModel.ProductName
	product.ProductDesc = productModel.ProductDesc
	product.ProductNum = productModel.ProductNum
	product.ProductPrice = productModel.ProductPrice
	product.ProductImg = productModel.ProductImg
	product.ProductVideo = productModel.ProductVideo
	return nil
}

func (product *ShopProduct) Add() error {
	conn := dbconnector.GetDb()
	conn = conn.Begin()
	if product.ProductId != 0 {
		conn.Rollback()
		return fmt.Errorf("商品分类id不为0，不可新增")
	}
	productModel := model.ShopProduct{
		ProductName:  product.ProductName,
		ProductDesc:  product.ProductDesc,
		ProductNum:   product.ProductNum,
		ProductPrice: product.ProductPrice,
	}
	sameNameProductModel := model.ShopProduct{}
	result := conn.Where("product_name", productModel.ProductName).First(&sameNameProductModel)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			result = conn.Create(&productModel)
			if result.Error != nil {
				if errMySQL, ok := result.Error.(*mysql.MySQLError); ok {
					switch errMySQL.Number {
					case 1062:
						conn.Rollback()
						return fmt.Errorf("名称为%s的商品已存在,请重新输入", productModel.ProductName)
					default:
						log.Error(fmt.Sprintf("新增商品%s时发生错误%s", productModel.ProductName, result.Error))
						conn.Rollback()
						return fmt.Errorf("新增商品时发生未知错误")
					}
				}
			}
			product.ProductId = productModel.ProductId
		} else {
			log.Error(fmt.Sprintf("新增商品%s时发生错误%s", productModel.ProductName, result.Error))
			conn.Rollback()
			return fmt.Errorf("新增商品时发生未知错误")
		}

	} else {
		conn.Rollback()
		return fmt.Errorf("名称为%s的商品已存在,请重新输入", sameNameProductModel.ProductName)
	}
	conn.Commit()
	return nil
}

type ShopProductList struct {
	ProductList []ShopProduct
	TotalNum    int64
}

func (productList *ShopProductList) GetProductList(categoryId int, pageNum int, pageSize int) error {
	conn := dbconnector.GetDb()
	productModelList := make([]model.ShopProduct, 0)
	conn = conn.Table("shop_products")
	if categoryId != 0 {
		conn = conn.Joins("join product_category_relations on product_category_relations.product_id = shop_products.product_id")
		conn = conn.Where("product_category_relations.category_id = ?", categoryId)
	}
	var totalNum int64
	result := conn.Count(&totalNum)
	if result.Error != nil {
		log.Error(fmt.Sprintf("查询商品列表时发生错误, category_id:%d, pageNum:%d, pageSize:%d, err:%s", categoryId, pageNum, pageSize, result.Error))
		return fmt.Errorf("查询商品发生未知错误，请稍后再试")
	}
	conn = conn.Limit(pageSize)
	conn = conn.Offset((pageNum - 1) * pageSize)
	result = conn.Find(&productModelList)
	if result.Error != nil {
		log.Error(fmt.Sprintf("查询商品列表时发生错误, category_id:%d, pageNum:%d, pageSize:%d, err:%s", categoryId, pageNum, pageSize, result.Error))
		return fmt.Errorf("查询商品发生未知错误，请稍后再试")
	}
	for _, value := range productModelList {
		productEntity := ShopProduct{}
		productEntity.ProductId = value.ProductId
		productEntity.ProductName = value.ProductName
		productEntity.ProductNum = value.ProductNum
		productEntity.ProductDesc = value.ProductDesc
		productEntity.ProductPrice = value.ProductPrice
		productEntity.ProductImg = value.ProductImg
		productEntity.ProductVideo = value.ProductVideo
		productList.ProductList = append(productList.ProductList, productEntity)
	}
	productList.TotalNum = totalNum
	return nil
}
